<template>
  <div class="divBox">
    <el-card class="box-card">
      <el-button icon="el-icon-arrow-left" size="mini" class="pan-back-btn mb20" @click="back">返回</el-button>
      <el-form ref="formValidate" class="form" :model="formValidate" label-width="120px" :rules="ruleValidate"
        @submit.native.prevent>
        <div class="dividerTitle">
          <span class="title mr10">视频信息</span>
          <el-divider />
        </div>
        <el-row>
          <el-col v-bind="grid" class="mr50">
            <el-form-item label="标题：" prop="title" label-for="title">
              <el-input v-model="formValidate.title" placeholder="请输入" element-id="title" style="width: 90%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col v-bind="grid" class="mr50">
            <el-form-item label="封面：" prop="image_src">
              <div class="upLoadPicBox" @click="modalPicTap('1')">
                <div v-if="formValidate.image_src" class="pictrue">
                  <img :src="formValidate.image_src" />
                </div>
                <div v-else class="upLoad">
                  <i class="el-icon-camera cameraIconfont" />
                </div>
              </div>
            </el-form-item>
            <el-form-item label="视频：" prop="video_src">
              <el-input v-model="formValidate.video_src" placeholder="点击上传视频或链接"></el-input>
              <input ref="refid" type="file" style="display:none" @change="zh_uploadFile_change" />
              <div class="upLoadPicBox" @click="zh_uploadFile" v-if="!formValidate.video_src">
                <div class="upLoad">
                  <i class="el-icon-camera cameraIconfont" />
                </div>
              </div>
              <div v-show="formValidate.video_src" style="position:relative;">
                <video style="width:100%;height: 100%!important;border-radius: 10px;" :src="formValidate.video_src"
                  controls="controls" id="video">您的浏览器不支持 video 标签。</video>
                <i class="el-icon-error btndel" @click="handleRemove" />
              </div>
            </el-form-item>
            <el-form-item label="视频商品：">
              <span>{{ productdetails.store_name}}</span>
              <el-button type="primary" size="small" @click="selectProduct">选择商品</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col v-bind="grid" class="mr50">
            <el-form-item label="是否置顶：" prop="image_input">
              <div class="upLoadPicBox">
                <el-switch v-model="formValidate.hot" :active-value="1" :inactive-value="0" active-text="是"
                  inactive-text="否" />
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col v-bind="grid" class="mr50">
            <el-form-item label="视频状态：" prop="image_input">
              <div class="upLoadPicBox">
                <el-switch v-model="formValidate.status" :active-value="1" :inactive-value="0" active-text="显示"
                  inactive-text="不显示" />
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="dividerTitle">
          <span class="title">视频内容</span>
          <el-divider />
        </div>
        <el-form-item label="视频内容：" prop="des">
          <el-input v-model="formValidate.des" type="textarea" placeholder="请输入" style="width: 90%" />
        </el-form-item>
        <el-row></el-row>
        <el-button type="primary" class="submission" @click="onsubmit('formValidate')">提交</el-button>
      </el-form>
      <canvas id="mycanvas" style="display: none"></canvas>
    </el-card>
    <div class="suspension" v-if="showSuspension">
      <el-card class="card">
        <div slot="header" class="clearfix">
          <span>请选择商品</span>
          <el-button icon="el-icon-close" style="float: right;" size="small" circle
            @click="showSuspension = false"></el-button>
        </div>
        <el-form size="small" label-width="120px" :inline="true">
          <el-form-item label="平台商品分类：">
            <el-cascader v-model="postList.cate_id" class="selWidth" :options="categoryList" :props="increaseProps"
              clearable @change="CommodityList(postList.cate_id)" />
          </el-form-item>
          <el-form-item label="商品搜索">
            <el-input placeholder="请输入内容" v-model="searchValue">
              <el-button slot="append" icon="el-icon-search" @click="search"></el-button>
            </el-input>
            
          </el-form-item>
        </el-form>
        <div>
          <el-table :data="tableData.list" style="width: 100%" max-height="200">
            <el-table-column label="" width="65">
              <template slot-scope="scope">
                <el-radio class="radio" v-model="templateSelection" :label="scope.$index"
                  @change="Radio(scope.row)">&nbsp;</el-radio>
              </template>
            </el-table-column>
            <el-table-column prop="product_id" label="ID" min-width="50" />
            <el-table-column label="商品图" min-width="80">
              <template slot-scope="scope">
                <div class="demo-image__preview">
                  <el-image :src="scope.row.image" :preview-src-list="[scope.row.image]" />
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="store_name" label="商品名称" min-width="200" />
            <el-table-column prop="price" label="商品售价" min-width="90" />
            <el-table-column prop="svip_price" label="会员价" min-width="90">
              <template slot-scope="scope">
                <span>{{ scope.row.svip_price || '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="sales" label="销量" min-width="90" />
            <el-table-column prop="stock" label="库存" min-width="70" />
            <el-table-column prop="integral_total" label="积分抵扣" min-width="70" />
            <el-table-column prop="integral_price_total" label="积分抵扣金额" min-width="90" />
            <el-table-column prop="stock" label="标签" min-width="90">
              <template slot-scope="scope">
                <div v-for="(item, index) in scope.row.mer_labels" :key="index" class="label-list">{{ item.name }}</div>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination :page-size="10" layout="total,prev, pager, next" :total="tableData.count"
            @current-change="changeCurrent" />
        </div>
        <div style="position: absolute; bottom: 10px;right: 10px;">
          <el-button size="small" @click="cancellation">取消</el-button>
          <el-button type="primary" size="small" @click="showSuspension = false">确认</el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2021 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------
import { productGetTempKeysApi, productLstApi } from "@/api/product";
import { addVideo, getVideoInfo, deitVideoInfo, upLoadImg } from "@/api/buss";
import ueditorFrom from "@/components/ueditorFrom";
import { roterPre } from "@/settings";
import {getCategory} from "@/api/diy"
export default {
  name: "EditArticle",
  components: { ueditorFrom },
  data() {
    return {
      showSuspension: false, // 悬浮窗
      tableData: {}, // 商品列表
      templateSelection: '', // 单选是否选中
      productId: '', // 商品ID
      productdetails: [],//选择的商品详情
      categoryList:[], // 平台商品分类
      searchValue:'', // 搜索内容
      increaseProps: {
        emitPath: false
      },
      postList: {
        page: 1,
        limit: 20,
        type: 1,
        cate_id:'',
        keyword:'',
      },
      roterPre: roterPre,
      grid: {
        xl: 10,
        lg: 10,
        md: 10,
        sm: 24,
        xs: 24
      },
      formValidate: {
        // 标题
        title: "",
        // 作者
        author: "",
        // 封面
        image_src: "",
        // 内容
        des: "",
        // 是否置顶
        hot: 0,
        // 视频状态
        status: 1,
        // 视频链接
        video_src: "",
        product_id: '',
      },
      ruleValidate: {
        title: [{ required: true, message: "请输入标题", trigger: "blur" }],
        image_src: [
          { required: true, message: "请上传视频封面", trigger: "blur" }
        ],
        video_src: [{ required: true, message: "请上传视频", trigger: "blur" }]
      },
      tempRoute: {},
      upload: {
        videoIng: false // 是否显示进度条；
      }
    };
  },
  watch: {
    $route(to, from) {
      if (this.$route.params.id) {
        this.getDetails();
      } else {
        this.formValidate = {
          // 标题
          title: "",
          // 作者
          author: "",
          // 封面
          image_src: "",
          // 内容
          des: "",
          // 是否置顶
          hot: 0,
          // 视频状态
          status: 1,
          // 视频链接
          video_src: ""
        };
      }
    }
  },
  created() {
    this.tempRoute = Object.assign({}, this.$route);
  },
  mounted() {
    console.log(this.$route.query.id);
    if (this.$route.query.id) {
      this.getDetails();
    }
  },
  methods: {
    // 取消
    cancellation(){
      this.showSuspension = false
      this.formValidate.product_id = ''
      this.productId = ''
      this.productdetails = ''
    },
    search(){
      this.postList = {
        page: 1,
        limit: 20,
        type: 1,
        cate_id:'',
        keyword:'',
      },
      this.postList.keyword = this.searchValue
      productLstApi(this.postList).then(res => {
        this.tableData = res.data
      })
    },
    // 筛选
    CommodityList(num){
      this.postList.cate_id = num
      productLstApi(this.postList).then(res => {
        this.tableData = res.data
      })
    },
    changeCurrent(value) {
      this.postList.page = value
      productLstApi(this.postList).then(res => {
        this.tableData = res.data
      })
    },
    Radio(row) { // 单选
      this.formValidate.product_id = row.product_id
      this.productId = row.product_id
      this.productdetails = row
    },
    selectProduct() { // 商品列表
      this.showSuspension = true
      productLstApi(this.postList).then(res => {
        this.tableData = res.data
      }).then(res=>{
        getCategory().then(req=>{
          this.categoryList = req.data
        })
      })
    },

    findvideocover(url, file) {
      const video = document.getElementById("video");
      var canvas = document.getElementById('mycanvas')
      // 获取 canvas 对象
      const ctx = canvas.getContext('2d'); // 绘制2d
      video.crossOrigin = 'anonymous' // 解决跨域问题，也就是提示污染资源无法转换视频
      video.currentTime = 1 // 第一帧
      video.oncanplay = () => {
        canvas.width = video.clientWidth; // 获取视频宽度
        canvas.height = video.clientHeight; //获取视频高度
        // 利用canvas对象方法绘图
        ctx.drawImage(video, 0, 0, video.clientWidth, video.clientHeight)
        // 转换成base64形式
        var imgsrc = canvas.toDataURL("image/png")
        // 截取后的视频封面
        // var twojz = this.base64ToBlob(imgsrc);
        upLoadImg({
          file: imgsrc
        }).then(res => {
          this.formValidate.image_src = res.data.src || res.data.url
        })
      }
    },
    base64ToBlob(base64) {
      var arr = base64.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], { type: mime });
      // var arr = base64.split(',');
      // var mime = arr[0].match(/:(.*?);/)[1] || 'image/png';
      // // 去掉url的头，并转化为byte
      // var bytes = window.atob(arr[1]);
      // // 处理异常,将ascii码小于0的转换为大于0
      // var ab = new ArrayBuffer(bytes.length);
      // // 生成视图（直接针对内存）：8位无符号整数，长度1个字节
      // var ia = new Uint8Array(ab);
      // for (var i = 0; i < bytes.length; i++) {
      //   ia[i] = bytes.charCodeAt(i);
      // }
      // return new Blob([ab], {
      //   type: mime
      // });
    },
    // 删除视频
    handleRemove() {
      this.formValidate.video_src = "";
    },
    // 点击上传视频按钮
    zh_uploadFile() {
      this.$refs.refid.click();
    },
    // 上传视频
    zh_uploadFile_change(evfile) {
      const that = this;
      that.progress = 10;
      const suffix = evfile.target.files[0].name.substr(
        evfile.target.files[0].name.indexOf(".")
      );
      if (suffix !== ".mp4") {
        return that.$message.error("只能上传MP4文件");
      }
      productGetTempKeysApi().then(res => {
        that.$videoCloud
          .videoUpload({
            type: res.data.type,
            evfile: evfile,
            res: res,
            uploading(status, progress) {
              console.log(status, "status");
              that.upload.videoIng = status;
            }
          })
          .then(res => {
            that.formValidate.video_src = res.url || res.data.src;
            that.$message.success("视频上传成功");
            that.progress = 100;
            that.findvideocover()
          })
          .catch(res => {
            that.upload.videoIng = false;
            that.$message.error(res);
          });
      });
    },
    // 上传图片
    modalPicTap(tit) {
      const _this = this;
      this.$modalUpload(function (img) {
        _this.formValidate.image_src = img[0];
      }, tit);
    },
    // 提交数据
    onsubmit(name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          if (this.$route.query.id) {
            deitVideoInfo(this.formValidate, this.$route.query.id)
              .then(async res => {
                this.$message.success(res.message);
                setTimeout(() => {
                  this.$router.push({ path: `${roterPre}/busines/video` });
                }, 500);
              })
              .catch(res => {
                this.$message.error(res.message);
              });
          } else {
            addVideo(this.formValidate)
              .then(async res => {
                this.$message.success(res.message);
                setTimeout(() => {
                  this.$router.push({ path: `${roterPre}/busines/video` });
                }, 500);
              })
              .catch(res => {
                this.$message.error(res.message);
              });
          }
        } else {
          return false;
        }
      });
    },
    // 返回
    back() {
      this.$router.push({ path: `${roterPre}/busines/video` });
    },
    // 视频详情
    getDetails() {
      getVideoInfo(this.$route.query.id ? this.$route.query.id : 0)
        .then(async res => {
          this.formValidate = res.data.info;
          this.productdetails.store_name = res.data.info.product.store_name
          // const news = res.data
          // this.sleOptions.title = news.articleCategory.title
          // this.sleOptions.article_category_id = news.articleCategory.article_category_id
          // this.formValidate = {
          //   cid: news.articleCategory.article_category_id,
          //   title: news.title,
          //   author: news.author,
          //   image_input: news.image_input,
          //   content: news.content.content,
          //   synopsis: news.synopsis,
          //   url: news.url,
          //   is_hot: news.is_hot,
          //   status: news.status
          // }
        })
        .catch(res => {
          this.loading = false;
          this.$message.error(res.message);
        });
    }
  }
};
</script>

<style scoped lang="scss">
.suspension {
  height: 100vh;
  width: 100vw;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 100;
  background-color: rgba($color: #000000, $alpha: 0.4);

  .card {
    height: 60vh;
    width: 50vw;
    position: fixed;
    top: 20vh;
    left: 25vw;
  }
}

/deep/ .el-pagination__jump {
  margin-left: 0;
}

/deep/.el-tree-node__content {
  height: 34px;
  font-weight: normal;
}

.btndel {
  position: absolute;
  z-index: 1;
  width: 20px !important;
  height: 20px !important;
  font-size: 23px;
  right: -4px;
  top: -4px;
  cursor: pointer;
  color: gainsboro;
}
</style>
